package db.tables;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import control.ConnectionManage;


/**
 * AdminCheckInOut manages all requests From,To table CheckIn And Table Checkout
 * @author Operations
 *
 */
public class AdminCheckInOut {

	private static Connection conn = ConnectionManage.getInstance()
			.getConnection();


	/**
	 * Insert new orders and its timestamp into Checkin DB table
	 * @param oid
	 * @param checkInTime
	 * @return
	 * @throws Exception
	 */
	public static boolean insertCheckIn(int oid,Timestamp checkInTime ) throws Exception {
		//AdminCheckInOut
		String sql = "INSERT into checkin (oid , timestamp) "
				+ "VALUES (?, ?)";
		ResultSet keys = null;
		try (PreparedStatement stmt = conn.prepareStatement(sql,
				Statement.RETURN_GENERATED_KEYS);) {

			stmt.setInt(1, oid);
			stmt.setTimestamp(2,checkInTime);
			int affected = stmt.executeUpdate();

			if (affected == 1) {
				keys = stmt.getGeneratedKeys();
				keys.next();
				int newKey = keys.getInt(1);
			} else {
				System.err.println("No rows affected");
				return false;
			}

		} catch (SQLException e) {
			System.err.println(e + "AdminCheackInOut->insertCheckIn");
			return false;
		} finally {
			if (keys != null)
				keys.close();
		}
		return true;

	}
	
	/**
	 * Insert new orders and its timestamp into CheckOut DB table
	 * @param oid
	 * @param checkInTime
	 * @return
	 * @throws Exception
	 */
	public static boolean insertCheckOut(int oid,Timestamp checkInTime ) throws Exception {
		//AdminCheckInOut
		String sql = "INSERT into checkout (oid , timestamp) "
				+ "VALUES (?, ?)";
		ResultSet keys = null;
		try (PreparedStatement stmt = conn.prepareStatement(sql,
				Statement.RETURN_GENERATED_KEYS);) {

			stmt.setInt(1, oid);
			stmt.setTimestamp(2,checkInTime);
			int affected = stmt.executeUpdate();

			if (affected == 1) {
				keys = stmt.getGeneratedKeys();
				keys.next();
				int newKey = keys.getInt(1);
			} else {
				System.err.println("No rows affected");
				return false;
			}

		} catch (SQLException e) {
			System.err.println(e + "AdminCheackInOut->insertCheckOut");
			return false;
		} finally {
			if (keys != null)
				keys.close();
		}
		return true;
	}
	
}
